package com.usian.kafka.stream;

import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.clients.producer.ProducerRecord;

import java.util.Properties;

public class WordCountProducer {

    private static final String TOPIC = "word-count-stream-topic";

    private static final String KAFKA_IP = "192.168.6.139:9092";

    public static void main(String[] args) throws InterruptedException {
        //添加kafka的配置信息
        Properties properties = new Properties();
        //配置broker信息
        properties.put("bootstrap.servers",KAFKA_IP);
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.RETRIES_CONFIG,10);
        properties.put(ProducerConfig.ACKS_CONFIG,"all");

        for (int i=1;i<100;i++){
            //         生产者对象
            KafkaProducer<String,String> producer = new KafkaProducer<String, String>(properties);
            //发送消息
            try {
                //封装消息
                if((i%2)==0){
                    ProducerRecord<String,String> record = new ProducerRecord<String, String>(TOPIC,"hello kafka usian!");
                    producer.send(record);
                }else{
                    ProducerRecord<String,String> record = new ProducerRecord<String, String>(TOPIC,"hi kafka stream !");
                    producer.send(record);
                }
            }catch (Exception e){
                e.printStackTrace();
            }
            //关闭消息通道
            producer.close();
            System.out.println("消息发送成功");
            Thread.sleep(2000);
        }


    }
}
